<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2021/01/14
 * Time: 17:10
 * @link http://www.lmterp.cn
 */

namespace app\common\behavior\finance;

use app\common\behavior\BaseBehavior;
use app\common\library\Tools;
use app\common\model\FinancePayment;
use app\common\model\JobFlowModule;
use app\common\model\Purchase;
use app\common\model\PurchaseExchange;
use app\common\model\PurchaseReturn;

/**
 * 付款回调
 * Class Payment
 * @package app\common\behavior\finance
 */
class Payment extends BaseBehavior
{
    /**
     * 付款数据模型
     * @var FinancePayment
     */
    protected $payment;

    /**
     * 付款单入口
     * @param FinancePayment $payment 付款单
     * @return bool|void
     * @date 2021/01/14
     * @author longli
     */
    public function run(FinancePayment $payment)
    {
        // 验证审批状态和付款状态
        if(!JobFlowModule::isCheckFinish($payment) || $payment->real_money <= 0) return;
        $method = Tools::toCamelCase($payment->getData('ref_type'));
        if(!method_exists($this, $method)) return;
        $this->payment = $payment;
        return $this->$method();
    }

    /**
     * 采购换货付款
     * @return bool|void
     * @date 2021/01/14
     * @author longli
     */
    protected function purchaseExchange()
    {
        $exchange = PurchaseExchange::getBySn($this->payment->ref_sn);
        if(empty($exchange)) return;
        $exchange->save(['is_pay' => PurchaseExchange::IS_YES]);
        return true;
    }

    /**
     * 采购退货
     * @return bool|void
     * @date 2021/01/14
     * @author longli
     */
    protected function purchaseReturn()
    {
        $ren = PurchaseReturn::get(['return_sn' => $this->payment->ref_sn]);
        if(empty($ren)) return;
        $ren->save(['is_pay' => PurchaseReturn::IS_YES]);
        return true;
    }

    /**
     * 采购单付款
     * @return bool|void
     * @date 2021/01/14
     * @author longli
     */
    protected function purchase()
    {
        $purchase = Purchase::getBySn($this->payment->ref_sn);
        if(empty($purchase)) return;
        // 更新采购单状态
        $purchase->pay_money += $this->payment->real_money;
        $purchase->pay_status = $purchase->total_money - $purchase->pay_money - $purchase->pro_money <= 0
            ? FinancePayment::PAY_STATUS_ALL
            : FinancePayment::PAY_STATUS_PART;
        $purchase->save();
        // 更新供应商状态
        if($purchase->producer) $purchase->producer->addPrice($this->payment->real_money);
        return true;
    }
}